#  Name:		cpuload
#  Version:		0.5
#  Depends:		awk
#  Part Of:		linuxrules
#  Purpose:		CPU system monitor capable of reading activity
#               for hipothetically any number of CPUs a system
#               throws at it, dynamically.
#
#  Notes:		It is supposed to use the one pass structure of
#				linuxrules, but depends on POSIX shared memory
#               in order to do its magic without sleep cycles.
#
#  Creation:	Fri Oct 08 2010 (Lost and rewritten for linuxrules)
#  Modified:	Wed Dec 01 2010, 19:57:29

# For GPL3 licensing information, refer to linuxrules COPYING file.

function read_current_stat () {
	idx = 0

	while ((getline < "/proc/stat") > 0) {
		if (/^cpu+[0-9]?[0-9]/)
		{
			idx++
			current[idx, 1] = ( $2 + $3 + $4 + $5 + $6 + $7 + $8)
			current[idx, 2] = ( $5 )
		}
	}
	close("/proc/stat")
}

BEGIN {
	NR = 1
	cpu_record	= "/dev/shm/cpuload.rec"
	read_current_stat()

	while ((NR SUBSEP 1) in current) {
        getline < cpu_record

		diffA = current[NR, 1] - $1
		diffI = current[NR, 2] - $2
        total = int(100 * (diffA - diffI) / diffA)

        # Simple / dummy check for any inconsistencies
        if ((total > 100) || (total < 0))
            total = 0

		_cpu["LOAD", NR - 1] = total

        # Memory record (about 16 bytes x cpu):
        # Never freed properly, but it is not
        # so nasty anyway.
		print current[NR, 1] " " current[NR, 2] > cpu_record

		NR++
	} 
    # DOUBLE CHECK
    close( cpu_record )
    close( cpu_record )
}
